//
//  GKHomeNet.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/9.
//  Copyright © 2018 wangws1990. All rights reserved.
//
//  电脑 + 衣服 +
import UIKit

class GKHomeNet {
    
    fileprivate static let manager = GKHomeNet()
    private var completion : ((_ options :GKLoadOptions) -> ())? = nil
    private lazy var listData: [GKHomeInfo] = []
    private lazy var arrayData : [GKHomeInfo] = []
    private var bookCase:GKHomeInfo? = nil
    func homeNet(options:GKLoadOptions,
                 sucesss:@escaping ((_ datas : [GKHomeInfo]) ->()),
                 failure:@escaping ((_ error : String) ->())){
        let group = DispatchGroup()
        if options.rawValue != 0 {
            if let listData = moya.client.rankDatas{
                self.arrayData.removeAll()
                listData.forEach { obj in
                    if let rankId = obj.rankId{
                        group.enter();
                        ApiMoya.request(target: .homeHot(rankId)) { json in
                            if let info = GKHomeInfo.deserialize(from: json["ranking"].rawString()){
                                if info.books.count > 0 {
                                    info.state = GKHomeInfoState.DataNet
                                    info.rankModel = obj
                                    self.arrayData.append(info);
                                }
                            }
                            group.leave()
                        } failure: { error in
                            group.leave()
                        }
                    }
                }
            }
        }
        if options.rawValue != 0 {
            group.enter()
            GKShelfData.getBookModels { (datas) in
                if datas.count > 0{
                    let info :GKHomeInfo = GKHomeInfo();
                    info.state = GKHomeInfoState.Database
                    info.books = datas
                    info.title = "我的书架"
                    info.shortTitle = "我的书架"
                    self.bookCase = info;
                }else{
                    self.bookCase = nil;
                }
                group.leave()
            }
        }
        group.notify(queue: DispatchQueue.main) {
            self.listData.removeAll();
            if let caseDatas = self.bookCase{
                self.listData.append(caseDatas)
            }
            if self.arrayData.count > 0 {
                self.listData.append(contentsOf: self.arrayData);
            }
            if self.listData.count > 0{
                sucesss(self.listData) ;
            }else{
                failure("数据空空如也");
            }
        }
    }
    static func reloadHomeData(options : GKLoadOptions){
        guard let com = GKHomeNet.manager.completion else { return  }
        com(options)
    }
    static func reloadHomeDataNeed(completion: @escaping ((_ options :GKLoadOptions) ->())){
        GKHomeNet.manager.completion = completion;
    }
}
